# encoding:utf-8

import os
import sys
import subprocess
import logging

# 分离出视频
STR_CMD1 = "{BIN} -i {basefile} -vcodec copy -an -y {tarfile}"

# 分离出音频
STR_CMD2 = "{BIN} -i {basefile} -acodec copy -vn -y {tarfile}"

# 切割（视频+音频）
STR_CMD3 = "{BIN} -ss {starttime} -t {endtime} -i {basefile} -vcodec copy -acodec copy -y {tarfile}"

# 切割（只留下视频）
STR_CMD4 = "{BIN} -ss {starttime} -t {endtime} -i {basefile} -vcodec copy -an -y {tarfile}"

# 纯视频了转换成gif
STR_CMD5 = "{BIN} -ss {starttime} -t {endtime} -i {basefile} -s {size} -f gif -y {tarfile}"


class Media():
    def __init__(self, bin):
        if bin.find("ffmpeg") == -1:
            logging.error("Need <ffmpeg executable> support!")
            sys.exit()
            return
        self._bin = bin

    def separate(self, mediafile, tarfile):
        str_cmd = STR_CMD1.replace("{BIN}", self._bin).replace(
            "{basefile}", mediafile).replace("{tarfile}", tarfile)
        logging.info("Separate the media's viewpart <%s> to <%s>" %
                     (mediafile, tarfile))

        return_code = subprocess.call(str_cmd, shell=True)

        if return_code != 0:
            logging.error(return_code)
            return

    def togif(self, mediafile, tarfile, starttime, endtime, sizew, sizeh):
        str_cmd = STR_CMD5.replace("{BIN}", self._bin).replace("{basefile}", mediafile).replace("{tarfile}", tarfile) \
            .replace("{starttime}", str(starttime)).replace("{endtime}", str(endtime)).replace("{size}", str(sizew) + "x" + str(sizeh))
        logging.info("Format the media <%s> to gif <%s>" %
                     (mediafile, tarfile))

        return_code = subprocess.call(str_cmd, shell=True)

        if return_code != 0:
            logging.error(return_code)
            return
